package com.kgcx.organization.service;

import com.github.pagehelper.PageHelper;
import com.kgcx.common.bean.RequestData;
import com.kgcx.common.constant.Cons;
import com.kgcx.common.utils.CollectionUtils;
import com.kgcx.dbutils.domain.BaseDomain;
import com.kgcx.dbutils.utils.PageUtils;
import com.kgcx.organization.domain.CustomerMsg;
import com.kgcx.organization.mapper.CustomerMsgMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 吴刚林
 * @date 2017/11/22
 */
@Service
public class CustomerMsgService {
    @Autowired
    private CustomerMsgMapper customerMsgMapper;


    public List<CustomerMsg> getCustomerMsgList(RequestData rd) {
        PageUtils.page(rd);
        PageHelper.orderBy(rd.getOrderBy());
        List<CustomerMsg> customerMsgList = customerMsgMapper.selectActive(BaseDomain.buildSelectDomain(rd, new CustomerMsg()));
        if (CollectionUtils.isNotEmpty(customerMsgList)) {
            List<Long> kids = customerMsgList.stream().map(CustomerMsg::getKid).collect(Collectors.toList());
            updateCustomerMsgIsRead(kids);
        }
        return customerMsgList;
    }


    public Integer getCustomerMsgUnreadCount(Long driverId) {

        CustomerMsg customerMsg = new CustomerMsg();
        customerMsg.setCustomerId(driverId);
        customerMsg.setIsRead(CustomerMsg.UNREAD);
        return customerMsgMapper.selectCountActive(customerMsg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addCustomerMsg(CustomerMsg customerMsg) {
        customerMsgMapper.insertSelective(customerMsg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateCustomerMsg(CustomerMsg customerMsg) {
        customerMsgMapper.updateByPrimaryKeySelective(customerMsg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeCustomerMsg(Long kid) {
        CustomerMsg customerMsg = new CustomerMsg();
        customerMsg.setKid(kid);
        customerMsg.setStatus(Cons.COMMON_STATUS_DELETE);
        customerMsgMapper.updateByPrimaryKeySelective(customerMsg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateCustomerMsgIsRead(List<Long> kids) {
        Example example = new Example(CustomerMsg.class);
        example.createCriteria().andIn("kid", kids);
        CustomerMsg customerMsgUpdate = new CustomerMsg();
        customerMsgUpdate.setIsRead(CustomerMsg.READ);
        customerMsgMapper.updateByExampleSelective(customerMsgUpdate, example);
    }

    @Transactional(rollbackFor = Exception.class)
    public void sendCustomerMsg(CustomerMsg customerMsg) {
        addCustomerMsg(customerMsg);
    }


}
